package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.model.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/quantity-inc-dec")
public class QuantityIncDecServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		try (PrintWriter out = response.getWriter()) {
			String action = request.getParameter("action");
			int id = Integer.parseInt(request.getParameter("id"));
			List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart");

			if (action != null && id >= 1) {
				if (action.equals("inc")) {
					for (CartItem item : cart) {
						if (item.getProduct().getProduct_id() == id) {
							item.setQuantity(item.getQuantity() + 1);
							break;
						}
					}
				}

				if (action.equals("dec")) {
					for (CartItem item : cart) {
						if (item.getProduct().getProduct_id() == id && item.getQuantity() > 1) {
							item.setQuantity(item.getQuantity() - 1);
							break;
						}
					}
				}
			}

			response.sendRedirect("cart.jsp");
		}
	}

}
